package com.example.xianji.activity;

import java.io.InputStream;
import java.net.URL;
import java.text.SimpleDateFormat;

import org.json.JSONException;
import org.json.JSONObject;

import com.example.xianji.Contant;
import com.example.xianji.R;
import com.example.xianji.widgets.CustomProgressDialog;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest.HttpMethod;

import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.Message;
import android.os.Build.VERSION;
import android.os.Build.VERSION_CODES;
import android.app.Activity;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.text.method.PasswordTransformationMethod;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

public class Main_Regester_twoActivity extends Activity implements OnClickListener {
    private ImageView register_two_step_back;
    private TextView text_phone;
    private Drawable d;
    private Button register_yanzheng, register_two;
    private ImageView register_imageview;
    private EditText tuxing_yanzheng, editText_password, editText_queren_password, editText_yanzhengma;
    private CustomProgressDialog mCustomProgressDialog;
    private TimeCount mTimeCount;
    private TextView register_two_login;
    private Handler handler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what == 1) {
                register_imageview.setImageDrawable(d);
            } else if (msg.what == 2) {
                if (mCustomProgressDialog != null) {
                    mCustomProgressDialog.dismiss();
                    mCustomProgressDialog = null;
                }
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (VERSION.SDK_INT >= VERSION_CODES.KITKAT) {
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
        }
        setContentView(R.layout.activity_main__regester_two);

        register_two_step_back = (ImageView) findViewById(R.id.register_two_step_back);
        text_phone = (TextView) findViewById(R.id.text_phone);
        register_imageview = (ImageView) findViewById(R.id.register_imageview);
        register_yanzheng = (Button) findViewById(R.id.register_yanzheng);
        tuxing_yanzheng = (EditText) findViewById(R.id.tuxing_yanzheng);
        editText_password = (EditText) findViewById(R.id.editText_password);
        editText_queren_password = (EditText) findViewById(R.id.editText_queren_password);
        editText_yanzhengma = (EditText) findViewById(R.id.editText_yanzhengma);
        register_two = (Button) findViewById(R.id.register_two);
        register_two_login = (TextView) findViewById(R.id.register_two_login);
        mTimeCount = new TimeCount(60000, 1000);
        editText_password.setTransformationMethod(PasswordTransformationMethod.getInstance());
        editText_queren_password.setTransformationMethod(PasswordTransformationMethod.getInstance());
        text_phone.setText(getIntent().getStringExtra("phone"));
        new Thread() {
            @Override
            public void run() {
                //把网络访问的代码放在这里
                LoadImageFromWebOperations(Contant.tuxing_yanzheng + getIntent().getStringExtra("phone"));
            }
        }.start();

        register_two_step_back.setOnClickListener(this);
        register_yanzheng.setOnClickListener(this);
        register_two.setOnClickListener(this);
        register_two_login.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.register_two_step_back) {
            Main_Regester_twoActivity.this.finish();
        } else if (v.getId() == R.id.register_yanzheng) {
            if (tuxing_yanzheng.getText().toString().length() > 0) {
                mTimeCount.start();
                huoqu_yanzhengma();
            } else {
                Toast.makeText(Main_Regester_twoActivity.this, "请输入图形验证码", 0).show();
            }
        } else if (v.getId() == R.id.register_two) {
            if (editText_yanzhengma.getText().toString().length() > 0) {
                if (editText_password.getText().toString().length() > 5) {
                    if (editText_password.getText().toString().equals(editText_queren_password.getText().toString())) {
                        mCustomProgressDialog = CustomProgressDialog.createDialog(Main_Regester_twoActivity.this);
                        mCustomProgressDialog.setCanceledOnTouchOutside(false);
                        mCustomProgressDialog.show();
                        register();
                    } else {
                        Toast.makeText(Main_Regester_twoActivity.this, "请输入6-20位的密码", 0).show();
                    }
                } else {
                    Toast.makeText(Main_Regester_twoActivity.this, "请保持两次输入密码一致", 0).show();
                }
            } else {
                Toast.makeText(Main_Regester_twoActivity.this, "请输入手机验证码", 0).show();
            }
        } else if (v.getId() == R.id.register_two_login) {
            startActivity(new Intent(Main_Regester_twoActivity.this, Main_LoginActivity.class));
        }
    }

    /**
     * 获取短信验证
     */
    public void huoqu_yanzhengma() {
        HttpUtils httpUtils = new HttpUtils();
        RequestParams parms = new RequestParams();
        parms.addBodyParameter("code_from", "register");
        parms.addBodyParameter("mobile", getIntent().getStringExtra("phone"));
        parms.addBodyParameter("picverify", tuxing_yanzheng.getText().toString());
        httpUtils.send(HttpMethod.POST, Contant.message_yanzheng, parms, new RequestCallBack<String>() {
            @Override
            public void onFailure(HttpException arg0, String arg1) {
            }

            @Override
            public void onSuccess(ResponseInfo<String> arg0) {
                try {
                    JSONObject obj = new JSONObject(arg0.result);
                    Toast.makeText(Main_Regester_twoActivity.this, obj.getString("msg"), 0).show();
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * 用户注册
     */
    public void register() {
        HttpUtils httpUtils = new HttpUtils();
        RequestParams parms = new RequestParams();
        parms.addBodyParameter("password", editText_password.getText().toString());
        parms.addBodyParameter("repassword", editText_queren_password.getText().toString());
        parms.addBodyParameter("mverify", editText_yanzhengma.getText().toString());

        parms.addBodyParameter("mobile", getIntent().getStringExtra("phone"));
        parms.addBodyParameter("picverify", tuxing_yanzheng.getText().toString());
        httpUtils.send(HttpMethod.POST, Contant.register, parms, new RequestCallBack<String>() {

            @Override
            public void onFailure(HttpException arg0, String arg1) {
                if (mCustomProgressDialog != null) {
                    mCustomProgressDialog.dismiss();
                    mCustomProgressDialog = null;
                }
            }

            @Override
            public void onSuccess(ResponseInfo<String> arg0) {
                try {
                    JSONObject obj = new JSONObject(arg0.result);
                    if (obj.getInt("status") == 1) {
                        Toast.makeText(Main_Regester_twoActivity.this, obj.getString("msg"), 0).show();
                        startActivity(new Intent(Main_Regester_twoActivity.this, Main_LoginActivity.class));
                        Main_Regester_twoActivity.this.finish();
                    } else {
                        Toast.makeText(Main_Regester_twoActivity.this, obj.getString("msg"), 0).show();
                    }
                    handler.sendEmptyMessage(2);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * 通过URL加载ImageView
     *
     * @param url
     * @return
     */
    private Drawable LoadImageFromWebOperations(String url) {
        try {
            InputStream is = (InputStream) new URL(url).getContent();
            d = Drawable.createFromStream(is, "src name");
            handler.sendEmptyMessage(1);
            return d;
        } catch (Exception e) {
            System.out.println("Exc=" + e);
            return null;
        }
    }

    class TimeCount extends CountDownTimer {
        public TimeCount(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
        }

        @Override
        public void onFinish() {
            register_yanzheng.setText("重新获取");
            register_yanzheng.setBackgroundDrawable(getResources().getDrawable(R.drawable.login_style));
        }

        @Override
        public void onTick(long millisUntilFinished) {
            String str = new SimpleDateFormat("ss").format(Long.valueOf(millisUntilFinished));
            if (str.equals("00")) {
                register_yanzheng.setText("60秒");
            }
            register_yanzheng.setText(str + "秒");
            register_yanzheng.setBackgroundDrawable(getResources().getDrawable(R.drawable.regiseter_huise_style));
        }
    }
}